<?php

namespace app\controller;

use app\BaseController;
use app\model\OrderModel;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\middleware\Check;
use think\validate\ValidateRule;
require_once '../sdk/WxpayAPI/lib/WxSend.Api.php';
require_once '../sdk/API-PHP/API_PHP_DEMO.php';
/**
 * Class Order 商户端 订单控制器
 * @package app\controller
 */
class Order extends BaseController
{
    protected $middleware = [Check::class];

    /** 生成订单
     * @param Request $request
     */

    public function new_order(Request $request)
    {
        //$start = microtime(true);
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $store_id = $this->request->param('store_id');//商户ID
        $user_id = $this->request->param('user_id');//用户ID
        $pay_type = $this->request->param('pay_type');//支付类型
        $total = $this->request->param('total');//客户端总价
        $address_id = $this->request->param('address_id');//地址ID
        $delivery_price = $this->request->param('delivery_price');//配送费
        $remark = $this->request->param('remark');//订单备注
        if (is_null($pay_type) ||empty($address_id)|| empty($store_id) || empty($user_id) || empty($total) || empty($delivery_price)) return jsonFail('缺少参数');
//        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->field('id')->find();
        $cart_list = Db::table('eb_cart')
            ->alias('a')
            ->join('eb_cart_detail b', 'b.cart_id = a.id')
            ->join('eb_goods w', 'b.goods_id = w.id')
            ->where('a.store_id', $store_id)
            ->where('a.user_id', $user_id)
            ->field('b.goods_id,b.num,w.name,w.name,w.pic,w.price')
            ->select()->toArray();
        $total_back = 0;
        foreach ($cart_list as $key => $value) {
            $total_back += $value['num'] * $value['price'];
        }
        $store_info = Db::table("eb_store")->where('id',$store_id)->find();
        $now_time = date("H:i", time());
        if ($now_time >= $store_info['send_start'] && $now_time <= $store_info['send_end']) {//在营业时间
            if (round($total_back, 2) != $total) return jsonFail('总价不相同', $total_back);
            $order = create_order_no();//生成订单号
            $user_info = Db::table('eb_user')->alias('a')
                ->leftJoin('eb_school b', 'a.school_id = b.id')
                ->leftJoin('eb_user_address c', 'a.id = c.uid')
                ->field('a.id,a.pid,a.integral,a.school_id,b.operate_id,b.company,b.plat,b.operate,b.extension,b.plat_id,b.name,c.dormitory_id,c.name,c.phone,c.address')
                ->where('a.id',$user_id)
                ->where('c.id',$address_id)
                ->find();
            $dormitory_info = Db::table('eb_dormitory')->where('id', $user_info['dormitory_id'])->field('name')->find();
            $operate_info =  Db::table('eb_admin')->where('id', $user_info['operate_id'])->field('send_delaytime')->find();
            $regus_time = time()+$operate_info['send_delaytime']*60;
            $company = $user_info['company'];//配置公司百分比
            $plat = $user_info['plat'];//平台方百分比
            $operate = $user_info['operate'];//运营方百分比
            $extension = $user_info['extension'];//推广百分比
            $company_price = ceil(($total_back * ($company / 100) * 100)) / 100;
            $plat_price = round($total_back * ($plat / 100), 2);
            $operate_price = round($total_back * ($operate / 100), 2);
            if ($user_info['pid'] == 0) {//没有上级
                $extension_price = 0;
            } else {
                $extension_price = round($total_back * ($extension / 100), 2);
            }
            if ($pay_type == 1) {//余额支付
                if ($total > $user_info['integral']) return jsonFail('积分不够哦！');
                //加入订单表
                Db::startTrans();
                try {
                    $orderId = Db::table('eb_order')->insertGetId([
                        'code' => substr(microtime(), -6),//生成提货码
                        'pay_type' => $pay_type,//支付类型
                        'order_no' => $order,
                        'total_price' => $total_back + $delivery_price,//总价
                        'delivery_price' => $delivery_price,//配送费
                        'goods_price' => $total_back,//商品费用
                        'company_price' => $company_price,//公司提成
                        'plat_price' => $plat_price,//平台方提成
                        'plat_id' => $user_info['plat_id'],//平台方id
                        'operate_id' => $user_info['operate_id'],//运营方id
                        'pid' => $user_info['pid'],
                        'pid_price' => $extension_price != 0 ? $extension_price : 0,
                        'store_price' => $total_back - ($company_price + $plat_price + $operate_price + $extension_price),//商家方提成
                        'operate_price' => $operate_price,//运营方提成
                        'user_id' => $user_id,
                        'store_id' => $store_id,
                        'store_name' => $store_info['shop_name'],
                        'school_id' => $user_info['school_id'],
                        'dormitory_id' => $user_info['dormitory_id'],
                        'consignee_name' => $user_info['name'],
                        'consignee_phone' => $user_info['phone'],
                        'consignee_address' => $user_info['name'].$dormitory_info['name'].$user_info['address'],
                        'remark' => $remark,
                        'is_pay' => 1,
                        'create_time' => time(),
                        'regus_time'=>$regus_time,
                    ]);
                    if ($orderId != 0) {
                        foreach ($cart_list as $key => $value) {
                            $res = Db::table('eb_order_detail')->insertGetId([
                                'order_id' => $orderId,
                                'goods_id' => $value['goods_id'],
                                'goods_name' => $value['name'],
                                'goods_num' => $value['num'],
                                'goods_price' => $value['price'],
                                'create_time' => time(),
                            ]);
                            if (empty($res)) return jsonFail('生成订单失败！');
                        }
                        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->find();
                        $ress = Db::table('eb_cart_detail')->where('cart_id', $cart['id'])->delete();
                        if ($ress) {
                            $res = Db::table('eb_cart')->where('id', $cart['id'])->delete();
                        }
                        $red = Db::table('eb_user')->where('id', $user_id)->dec('integral', $total_back + $delivery_price)->update();
                        if ($red != 0) {//余额扣款成功
                            Db::commit();
                        }
                        $order_info = Db::table('eb_order')->where('id', $orderId)->find();
                        $order_list = Db::table('eb_order_detail')
                            ->alias('a')
                            ->leftJoin('eb_goods b', 'a.goods_id = b.id')
                            ->where('a.order_id', $orderId)
                            ->field('a.*,b.*')
                            ->select()->toArray();
                        $send = new \API_PHP_DEMO();
                        $data = combination($store_info, $user_info, $order_info, $order_list, 14, 6, 3, 6);
                        $code = $send->printMsg($store_info['sn'], $data);
                        $datas = json_decode($code, true);
                        if ($datas['ret'] == 0) {//通知商家成功
                            $res = Db::table('eb_order')->where('id', $orderId)->update(['status' => 1]);
                            //通知骑手
                            $list = Db::table('eb_user')->where('school_id', $user_info['school_id'])->where('delivery_type', 0)->where('type', '<>', 1)->select()->toArray();
                            $send = new \WxSendApi();
                            foreach ($list as $key => $value) {
                                $delivery_storieds = explode(',', $value['delivery_storied']);
                                if (in_array($user_info['dormitory_id'], $delivery_storieds)) {
                                    $ds = json_decode($send->send_Template_rider($value, $order_info), true);//通知骑手
                                }
                            }
//                            var_dump(microtime(true)-$start);
                            if ($res) return jsonSuccess('积分抵扣成功！', ['order_no' => $order], 202);
                            return jsonFail('余额抵扣失败');
                        } else {
                            return jsonSuccess('积分抵扣成功！', ['order_no' => $order], 202);
                        }
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    return jsonFail($e->getMessage());
                }
            } else {
                //加入订单表
                Db::startTrans();
                try {
                    $orderId = Db::table('eb_order')->insertGetId([
                        'code' => substr(microtime(), -6),//生成提货码
                        'pay_type' => $pay_type,//支付类型
                        'order_no' => $order,
                        'total_price' => $total_back + $delivery_price,//总价
                        'delivery_price' => $delivery_price,//配送费
                        'goods_price' => $total_back,//商品费用
                        'company_price' => $company_price,//公司提成
                        'plat_price' => $plat_price,//平台方提成
                        'plat_id' => $user_info['plat_id'],//平台方id
                        'operate_id' => $user_info['operate_id'],//运营方id
                        'pid' => $user_info['pid'],
                        'pid_price' => $extension_price != 0 ? $extension_price : 0,
                        'store_price' => $total_back - ($company_price + $plat_price + $operate_price + $extension_price),//商家方提成
                        'operate_price' => $operate_price,//运营方提成
                        'user_id' => $user_id,
                        'store_id' => $store_id,
                        'store_name' => $store_info['shop_name'],
                        'school_id' => $user_info['school_id'],
                        'dormitory_id' => $user_info['dormitory_id'],
                        'consignee_name' => $user_info['name'],
                        'consignee_phone' => $user_info['phone'],
                        'consignee_address' => $user_info['name'].$dormitory_info['name'].$user_info['address'],
                        'remark' => $remark,
                        'create_time' => time(),
                        'regus_time'=>$regus_time,
                    ]);
                    if ($orderId != 0) {
                        foreach ($cart_list as $key => $value) {
                            $res = Db::table('eb_order_detail')->insertGetId([
                                'order_id' => $orderId,
                                'goods_id' => $value['goods_id'],
                                'goods_name' => $value['name'],
                                'goods_num' => $value['num'],
                                'goods_price' => $value['price'],
                                'create_time' => time(),
                            ]);
                            if (empty($res)) {
                                Db::rollback();
                                return jsonFail('生成订单失败！');
                            }
                        }
                        $cart = Db::table('eb_cart')->where('store_id', $store_id)->where('user_id', $user_id)->find();
                        $ress = Db::table('eb_cart_detail')->where('cart_id', $cart['id'])->delete();
                        if ($ress) {
                            $red = Db::table('eb_cart')->where('id', $cart['id'])->delete();
                        }
                        if ($orderId != 0 && $red!=0)  {
//                        if ($orderId != 0 && $res !=0 )  {
                            Db::commit();
//                            file_put_contents('/tmp/a.txt', microtime(true)-$start . PHP_EOL, FILE_APPEND);
//                            var_dump(microtime(true)-$start);
                            return jsonSuccess('生成订单成功！', ['order_no' => $order]);
                        }else{
                            Db::rollback();
                            return jsonFail('生成订单失败！');
                        }
                    }
                } catch (\Exception $e) {
                    return jsonFail($e->getMessage());
                }
            }
        }else{
            return jsonFail('不在配送时间段，请更改时间段下单哦');
        }
    }

    /** 获取所有订单
     * @param Request $request
     */
    public function order_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $page = $this->request->param('page',1);//
        $limit = $this->request->param('limit',20);//用户ID
        if (empty($user_id)) return jsonFail('缺少用户ID');
        $data = Db::table('eb_order')->where('user_id', $user_id)->order('create_time', 'desc')->page($page,$limit)->select()->toArray();
        foreach ($data as $key => &$value) {
//            $value['school_name'] = Db::table('eb_school')->where('id', $value['school_id'])->field('name')->find();
//            $value['dormitory_name'] = Db::table('eb_dormitory')->where('id', $value['dormitory_id'])->field('name')->find();
            $value['order_detail'] = Db::table('eb_order_detail')->where('order_id', $value['id'])->select()->toArray();
            $value['store'] = Db::table('eb_store')->where('id', $value['store_id'])->field('id,shop_name,logo,bank_phone,is_refues')->find();
            foreach ($value['order_detail'] as $key1 => &$value1) {
                $value1['goods'] = Db::table('eb_goods')->where('id', $value1['goods_id'])->select()->toArray();
            }
            if (!is_null($value['send_id'])) {//有配送员
                $value['send'] = Db::table('eb_user')->where('id', $value['send_id'])->field('name,phone')->find();
            }
        }
        return jsonSuccess('获取成功', $data);
    }

    /**用户评论订单、评价
     * @param Request $request
     * @return \think\response\Json
     */
    public function comment(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单编号
        $store_comment = $this->request->param('store_comment', '');//商家评论
        $store_score = $this->request->param('store_score');//商家评分
        $send_comment = $this->request->param('send_comment', '');//送货员评论
        $send_score = $this->request->param('send_score');//商家评分
        if (empty($send_score) || empty($store_score)) return jsonFail('缺少参数');
        if ($store_score > 10) return jsonFail('满分10，请检查评分！');
        if ($send_score > 10) return jsonFail('满分10，请检查评分！');
        $order = Db::table('eb_order')->where('order_no', $order_no)->find();
        if (empty($order)) return jsonFail('暂无订单');
        try {
            Db::startTrans();
            $res = Db::table('eb_order')->where('order_no', $order_no)->update(['comment' => $store_comment, 'status' => 6]);
            $mark_id = Db::table('eb_mark')->insertGetId(['order_no' => $order_no, 'type' => 1, 'score' => $store_score, 'sid' => $order['store_id']]);
            if ($mark_id != 0) {
                $avg = Db::table('eb_mark')->where('type', 1)->where('sid', $order['store_id'])->avg('score');
                Db::table('eb_store')->where('id', $order['store_id'])->update(['score' => $avg]);
            } else {
                return jsonFail('评价失败');
            }
            $mark_ids = Db::table('eb_mark')->insertGetId(['order_no' => $order_no, 'type' => 2, 'score' => $send_score, 'sid' => $order['send_id'], 'comment' => $send_comment]);
            if ($mark_ids){
                Db::commit();
                return jsonSuccess('评价成功');
            }
            Db::rollback();
            return jsonFail('评价失败');
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail('系统错误~');
        }
    }

    /**商户获取自己订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function storeGetList(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $input['page'] = $request->post('page'); // 当前页
        $input['limit'] = $request->post('limit'); // 每页显示数量
        //验证参数
        $validate = Validate::rule([
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return OrderModel::storeGetList($input, $request->param('token'));
    }

    /**根据状态商户获取自己订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function statusGetList(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $input['page'] = $request->post('page'); // 当前页
        $input['limit'] = $request->post('limit'); // 每页显示数量
        $input['status'] = $request->post('status'); // 状态
        //验证参数
        $validate = Validate::rule([
            'page' => ValidateRule::isRequire(null, '缺少参数'),
            'limit' => ValidateRule::isRequire(null, '缺少参数'),
            'status' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        return OrderModel::statusGetList($input, $request->param('token'));
    }

    /**用户申请退款
     * @param Request $request
     * @return \think\response\Json
     */
    public function Apply_refund(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $order_no = $request->post('order_no'); //订单号
        $back_reason = $request->post('back_reason'); //退款原因
        if(empty($order_no)||empty($back_reason)) return jsonFail('缺少参数');
        try {
            $send = new \API_PHP_DEMO();
            $store = Db::table('eb_order')->alias('a')->leftJoin('eb_store b', 'a.store_id = b.id')->where('a.order_no',$order_no)->field('b.sn');
            $res = Db::table('eb_order')->where('order_no',$order_no)->update(['status'=>-1,'back_reason'=>$back_reason]);
            $data = combination_cancel(14, 6, 3, 6);
            $code = $send->printMsg($store['sn'], $data);
            if($res!=0) return jsonSuccess('申请成功');
            return jsonFail('申请失败');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }
    /** 查询当前订单信息
     * @param Request $request
     */
    public function order_info(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        // 接收参数
        $order_no = $request->post('order_no'); //订单号
        $data = Db::table('eb_order')->alias('a')
            ->leftJoin('eb_user b', 'a.send_id = b.id')
            ->leftJoin('eb_store c', 'a.store_id = c.id')
            ->where('a.order_no', $order_no)
            ->field('a.*,b.name as send_name,b.phone as send_phone,c.bank_phone,c.shop_name')->find();
        $data['goods'] = Db::table('eb_order_detail')->alias('a')
            ->leftJoin('eb_goods b', 'a.goods_id = b.id')
            ->where('a.order_id',$data['id'])
            ->field('a.goods_num,a.goods_num * a.goods_price as amount,b.name')->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /** 根据条件所有订单
     * @param Request $request
     */
    public function find_order_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $page = $this->request->param('page',1);//
        $limit = $this->request->param('limit',20);//用户ID
        $text = $this->request->param('text');//搜索内容
        if (empty($user_id)) return jsonFail('缺少用户ID');
        if(empty($text)) return jsonSuccess('获取成功', []);
        $order = Db::table('eb_order')->alias('a')
            ->join('eb_order_detail b', 'a.id = b.order_id')
            ->join('eb_store c', 'a.store_id = c.id')
            ->join('eb_user d', 'a.send_id = d.id')
            ->whereRaw(" `a`.`user_id` = {$user_id} AND ( `a`.`store_name` LIKE '%{$text}%'   OR  `b`.`goods_name` LIKE '%{$text}%' )")
            ->page($page,$limit)
            ->field('a.pay_type,a.send_id,d.phone as send_phone,a.status,a.create_time,c.id,a.order_no,b.goods_num * b.goods_price as amount,c.shop_name,c.logo,c.bank_phone')
            ->select()
            ->toArray();

        foreach ($order as $key=>&$value){
            $order[$key]['store']['id'] = $value['id'];
            $order[$key]['store']['shop_name'] = $value['shop_name'];
            $order[$key]['store']['logo'] = $value['logo'];
            if(array_key_exists($value['send_id'],$order)){
                $order[$key]['send']['phone'] = $value['send_phone'];
                unset($value['send_phone']);
            }
            unset($value['id']);
            unset($value['shop_name']);
            unset($value['logo']);
            unset($value['send_id']);
        }
        return jsonSuccess('获取成功', $order);
    }
}
